package com.gexiaobao.pigeon.ui.fragment.mall

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.graphics.Rect
import android.os.Bundle
import android.text.TextUtils
import android.util.TypedValue
import android.view.KeyEvent
import android.view.LayoutInflater
import android.view.View
import androidx.core.view.isVisible
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.model.bean.CarouselListResponse
import com.gexiaobao.pigeon.app.model.bean.GoodsTypeParentResponse
import com.gexiaobao.pigeon.app.util.DatetimeUtil
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentShopHomePageBinding
import com.gexiaobao.pigeon.ui.adapter.FatherTypeAdapter
import com.gexiaobao.pigeon.ui.adapter.FlashSaleAdapter
import com.gexiaobao.pigeon.ui.adapter.HotGoodsAdapter
import com.gexiaobao.pigeon.ui.adapter.ImageAdapter
import com.gexiaobao.pigeon.ui.adapter.MallProductAdapter
import com.gexiaobao.pigeon.ui.adapter.TopicAdapter
import com.gexiaobao.pigeon.ui.fragment.mall.db.RecordsDao
import com.gexiaobao.pigeon.ui.mall.MallViewModel
import com.kingja.loadsir.core.LoadService
import com.loan.golden.cash.money.interval.Interval
import com.loan.golden.cash.money.interval.IntervalStatus
import com.youth.banner.indicator.CircleIndicator
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import java.util.concurrent.TimeUnit


/**
 * @Author      : hxw
 * @Date        : 2023/6/26 13:44
 * @Describe    : 商城
 */
class FragmentShopHomePage : BaseFragment<MallViewModel, FragmentShopHomePageBinding>(), TopicAdapter.OnItemClickListener {

    private var headerView: View? = null
    private val data: ArrayList<GoodsTypeParentResponse.ListBean> = arrayListOf()
    private var bannerImgList: ArrayList<String> = arrayListOf()

    private val mAdapter: MallProductAdapter by lazy { MallProductAdapter(arrayListOf()) }
    private val mHotAdapter: HotGoodsAdapter by lazy { HotGoodsAdapter(arrayListOf()) }
    private val flashSaleAdapter: FlashSaleAdapter by lazy { FlashSaleAdapter(arrayListOf()) }
    private val fatherAdapter: FatherTypeAdapter by lazy { FatherTypeAdapter(arrayListOf()) }
    private lateinit var loadsir: LoadService<Any>
    private var chooseTimesId: Int = 0

    private var mRecordsDao: RecordsDao? = null
    private lateinit var interval: Interval // 轮询器

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    override fun onResume() {
        super.onResume()
        activity?.let { StatusBarUtil.setLightMode(it) }
        activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
    }

    /**
     * 判断是否是初始化Fragment
     */
    private var mIsHasStarted = false

    /**
     * 本方法会在ViewPager + Fragment结合时会执行
     * 初始化时会执行两次，一次在 onCreate 之前 isVisibleToUser 为false，
     * 另一次在 onCreate 之后 isVisibleToUser 为true
     * @param isVisibleToUser
     */
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if (isVisibleToUser) {
            activity?.let { StatusBarUtil.setLightMode(it) }
            activity?.let { StatusBarUtil.setColor(it, Color.TRANSPARENT, 0) }
        } else {
            if (mIsHasStarted) {
                mIsHasStarted = false
            }
        }
    }

    override fun initView(savedInstanceState: Bundle?) {
        //默认账号
        val username = "007"
        //初始化数据库
        mRecordsDao = RecordsDao(context, username)

        mDatabind.recyclerViewFlashSale.layoutManager = LinearLayoutManager(context, RecyclerView.HORIZONTAL, false)
        mDatabind.recyclerViewFlashSale.adapter = flashSaleAdapter
        // 添加间距 ItemDecoration
        mDatabind.recyclerViewFlashSale.addItemDecoration(SpaceItemDecoration(leftRight = 20, topBottom = 0))

        /** 正在热卖 */
        val layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
        mDatabind.swipeRecyclerViewHot.addItemDecoration(object : RecyclerView.ItemDecoration() {
            override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
                super.getItemOffsets(outRect, view, parent, state)
                outRect.right = Util.dp2px(context, 5f)//右间距5dp
                outRect.left = Util.dp2px(context, 5f)//左间距5dp
                outRect.top = Util.dp2px(context, 5f)//上间距5dp
                outRect.bottom = Util.dp2px(context, 5f)//下间距5dp
            }
        })
        headerView = LayoutInflater.from(context).inflate(R.layout.header_layout_hot_goods, null)
        if (headerView != null) {
            mHotAdapter.setHeaderView(headerView!!)
        }
        mDatabind.swipeRecyclerViewHot.layoutManager = layoutManager
        mDatabind.swipeRecyclerViewHot.adapter = mHotAdapter

        mDatabind.swipeRecyclerView.init(GridLayoutManager(context, 2), mAdapter)

        mDatabind.recyclerViewFatherType.init(GridLayoutManager(context, 2), fatherAdapter)

        //状态页配置
        loadsir = loadServiceInit(mDatabind.swipeRefreshLayout) {
            //点击重试时触发的操作
            onRefresh()
        }

        mDatabind.swipeRefreshLayout.init {
            onRefresh()
        }

        fatherAdapter.setOnItemClickListener { _, _, position ->
            nav().navigateAction(R.id.action_to_fragment_mall_goods, Bundle().apply {
                putInt("index", position)
            })
        }

        mHotAdapter.setOnItemClickListener { _, _, position ->
//            startActivity<ActivityGoodsDetail>("id" to mHotAdapter.data[position].goodsId.toString())
            nav().navigateAction(R.id.action_to_fragment_goods_detail, Bundle().apply {
                putString("id", mHotAdapter.data[position].goodsId.toString())
            })
        }

        mAdapter.addChildClickViewIds(R.id.llGoToMerchantStore, R.id.riv_item_icon)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.llGoToMerchantStore -> {
                    nav().navigateAction(R.id.action_to_fragment_merchant_store, Bundle().apply {
                        putInt("shopId", mAdapter.data[position].shopId)
                    })
                }

                R.id.riv_item_icon -> {
//                    startActivity<ActivityGoodsDetail>("id" to mAdapter.data[position].id.toString())
                    nav().navigateAction(R.id.action_to_fragment_goods_detail, Bundle().apply {
                        putString("id", mAdapter.data[position].id.toString())
                    })
                }
            }
        }

        mDatabind.editQuery.setOnKeyListener { _, keyCode, event ->
            if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == KeyEvent.ACTION_DOWN) {
                if (!TextUtils.isEmpty(mDatabind.editQuery.text.toString())) {
                    searchGoods()
                } else {
                    RxToast.showToast("请输入需要搜索的内容")
                }
                hideSoftKeyboard(activity)
            }
            false
        }

        flashSaleAdapter.setOnItemClickListener { _, _, _ ->
            nav().navigateAction(R.id.action_to_flash_sale_fragment, Bundle().apply {
                putInt("timesId", chooseTimesId)
            })
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        onRefresh()
        mViewModel.getGoodTypeFatherList("0")
    }

    private fun searchGoods() {
        val record = mDatabind.editQuery.text.toString().trim()
        if (record.isNotEmpty()) {
            //添加数据
            mRecordsDao!!.addRecords(record)
        }
        nav().navigateAction(R.id.action_to_fragment_search_result, Bundle().apply {
            putString("searchContent", record)
            putString("type", "1")
        })
    }

    private fun onRefresh() {
        mViewModel.getCarouselList()
        /** 请求轮播图 */
        mViewModel.getSaleList()
        mViewModel.getHotSaleList()
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()

        /** 获取热卖商品列表 */
        mViewModel.HotGoodsListResult.observe(viewLifecycleOwner) {
            headerView!!.isVisible = !it.isEmpty()
            mDatabind.swipeRefreshLayout.isRefreshing = false
            mHotAdapter.setList(it.list)
            mHotAdapter.notifyDataSetChanged()
        }
        /** 获取限时抢购列表 */
        mViewModel.saleListResult.observe(viewLifecycleOwner) { it ->
            mDatabind.swipeRefreshLayout.isRefreshing = false
            if (it != null) {
                chooseTimesId = it.id
                mDatabind.llFlashSale.isVisible = !it.isEmpty()
                /** 1-未开始2-进行中3-已结束 */
                if (it.state == 1) {
                    mDatabind.tvFlashSaleTitle.text = "开始时间"
                    mDatabind.tvFlashSaleTimeCount.text = it.startTime
                    if (::interval.isInitialized) {
                        interval.cancel()
                    }
                } else if (it.state == 2) {
                    mDatabind.tvFlashSaleTitle.text = "距离结束"
                    if (::interval.isInitialized && interval.state == IntervalStatus.STATE_ACTIVE) {
                        interval.cancel()
                    }
                    /** 自定义计数器个数的轮询器, 当 start 比 end 值大, 且end不等于-1时, 即为倒计时 */
                    interval = Interval(0, 1, TimeUnit.SECONDS, it.countDown).life(this)
                    interval.subscribe {
                        mDatabind.tvFlashSaleTimeCount.text = DatetimeUtil.formatDateTime2(it)
                    }.finish {
                        mViewModel.getSaleList()
                    }.start()
                }
                flashSaleAdapter.setList(it.list)
                flashSaleAdapter.notifyDataSetChanged()
            }
        }
        /** 获取轮播图资源 */
        mViewModel.carouselListResult.observe(viewLifecycleOwner) {
            if (it == null || it.isEmpty()) {
                RxToast.showToast("获取分类父列表为空")
                return@observe
            }
            initBanner(it.list)
        }

        /** 获取分类父列表  */
        mViewModel.goodsTypeParentResult.observe(viewLifecycleOwner) {
//            dismissLoading()
            if (it.isEmpty()) {
                RxToast.showToast("获取分类父列表为空")
                return@observe
            }
            data.clear()
            data.addAll(it.list)
            fatherAdapter.setList(data)
            fatherAdapter.notifyDataSetChanged()
            initTopicData(it.list)
        }
        /** 查询订单列表 */
        mViewModel.goodsListResult.observe(viewLifecycleOwner) {
//            dismissLoading()
            mDatabind.swipeRefreshLayout.isRefreshing = false
            mAdapter.setList(it.listData)
            mAdapter.notifyDataSetChanged()
        }
    }

    private fun initBanner(it: ArrayList<CarouselListResponse.ListBean>) {
        bannerImgList.clear()
        it.forEachIndexed { _, listBean ->
            bannerImgList.add(listBean.img)
        }
        mDatabind.bannerShopHome.addBannerLifecycleObserver(this)//添加生命周期观察者
            .setAdapter(ImageAdapter(bannerImgList)).setIndicator(CircleIndicator(context))
            .setLoopTime(5000).setOnBannerListener { data, position ->
                if (data.toString().isEmpty()) {
                    RxToast.showToast("图片资源获取失败")
                    return@setOnBannerListener
                }
                if (it[position].goId != 0) {
//                    startActivity<ActivityGoodsDetail>("id" to it[position].goId.toString())
                    nav().navigateAction(R.id.action_to_fragment_goods_detail, Bundle().apply {
                        putString("id", it[position].goId.toString())
                    })
                }
            }
        mDatabind.bannerShopHome.setBannerRound(20F)
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.ivBack, mDatabind.tvSearch, mDatabind.tvMallPageMine, mDatabind.llFlashSale) {
            when (it) {
                mDatabind.ivBack -> nav().navigateUp()
                mDatabind.tvSearch -> searchGoods()
//                mDatabind.tvMallPageMine -> {}//nav().navigateAction(R.id.action_to_fragment_personal_center
                mDatabind.llFlashSale -> {
                    nav().navigateAction(R.id.action_to_flash_sale_fragment, Bundle().apply {
                        putInt("timesId", chooseTimesId)
                    })
                }
            }
        }
    }

    private fun initTopicData(list: ArrayList<GoodsTypeParentResponse.ListBean>) {
        if (list.isNotEmpty()) {
            for (position in 0 until list.size) {
                data[position] = GoodsTypeParentResponse.ListBean(
                    image = data[position].img,
                    goodTypeName = data[position].goodTypeName,
                    goodTypeDescription = data[position].goodTypeDescription,
                    id = data[position].id,
                    sort = data[position].sort
                )
            }
        }
//        initTypeViewPager(2, 4)
    }

//    private fun initTypeViewPager(rowNum: Int, columnNum: Int) {
//        //1.rowNum行数；columnNum列数
//        //2.根据数据的多少来分页，每页的数据为rw
//        val singlePageDatasNum: Int = rowNum * columnNum //每个单页包含的数据量：2*4=8
//        var pageNum: Int = data.size / singlePageDatasNum //算出有几页菜单：20%8 = 3
//        if (data.size % singlePageDatasNum > 0) pageNum++ //如果取模大于0，就还要多一页出来，放剩下的不满项
//        val mList = ArrayList<RecyclerView>()
//        for (i in 0 until pageNum) {
//            val recyclerView = context?.let { RecyclerView(it) }
//            val gridLayoutManager = GridLayoutManager(context, columnNum)
//            recyclerView?.layoutManager = gridLayoutManager
//            val fromIndex = i * singlePageDatasNum
//            var toIndex = (i + 1) * singlePageDatasNum
//            if (toIndex > data.size) toIndex = data.size
//            //a.截取每个页面包含数据
//            val menuItems: ArrayList<GoodsTypeParentResponse.ListBean> = ArrayList(data.subList(fromIndex, toIndex))
//            //b.设置每个页面的适配器数据
//            val menuAdapter = TopicAdapter(context, menuItems)
//            menuAdapter.setOnItemClickListener(this)
//            //c.绑定适配器，并添加到list
//            recyclerView?.adapter = menuAdapter
//            if (recyclerView != null) {
//                mList.add(recyclerView)
//            }
//        }
//        //2.ViewPager的适配器
//        val menuViewPagerAdapter = HomeTopicPagerAdapter(mList)
//        mDatabind.topicViewPager.adapter = menuViewPagerAdapter
//        //3.动态设置ViewPager的高度，并加载所有页面
//        val height: Int = context?.let { dp2px(it, 96.0f) }!! //这里的80为MainMenuAdapter中布局文件高度
//        val layoutParams =
//            LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, if (data.size <= columnNum) height else height * rowNum)
//        mDatabind.topicViewPager.layoutParams = layoutParams
//        mDatabind.topicViewPager.offscreenPageLimit = pageNum - 1
//        //4.创建指示器
//        val commonNavigator = CommonNavigator(context)
//        commonNavigator.isAdjustMode = true
//        val finalPageNum = pageNum
//        commonNavigator.adapter = object : CommonNavigatorAdapter() {
//            override fun getCount(): Int {
//                return finalPageNum
//            }
//
//            override fun getTitleView(context: Context, index: Int): IPagerTitleView {
//                return DummyPagerTitleView(context)
//            }
//
//            override fun getIndicator(context: Context): IPagerIndicator {
//                val indicator = LinePagerIndicator(context)
//                indicator.mode = LinePagerIndicator.MODE_EXACTLY
//                indicator.lineHeight = UIUtil.dip2px(context, 3.0).toFloat() //就是指示器的高
//                indicator.lineWidth = UIUtil.dip2px(context, (30 / finalPageNum).toDouble()).toFloat() //就是指示器的宽度，然后通过页数来评分
//                indicator.roundRadius = UIUtil.dip2px(context, 3.0).toFloat()
//                indicator.startInterpolator = AccelerateInterpolator()
//                indicator.endInterpolator = DecelerateInterpolator(3f)
//                indicator.setColors(ContextCompat.getColor(context, R.color.color_red))
//                return indicator
//            }
//        }
//        //5.配置指示器，并和ViewPager产生绑定
//        mDatabind.topicIndicator.navigator = commonNavigator
//        ViewPagerHelper.bind(mDatabind.topicIndicator, mDatabind.topicViewPager)
//    }

    fun dp2px(context: Context, dpVal: Float): Int {
        return TypedValue.applyDimension(
            TypedValue.COMPLEX_UNIT_DIP,
            dpVal, context.resources.displayMetrics
        ).toInt()
    }

    override fun onTopicItemClick(position: Int, data: GoodsTypeParentResponse.ListBean?) {
        nav().navigateAction(R.id.action_to_fragment_mall_goods, Bundle().apply {
            putInt("index", position)
        })
    }

    override fun onStart() {
        super.onStart()
        mDatabind.bannerShopHome.start()
    }

    override fun onStop() {
        super.onStop()
        mDatabind.bannerShopHome.stop()
    }

    override fun onDestroy() {
        super.onDestroy()
        if (::interval.isInitialized) {
            interval.cancel()
            interval.stop()
            interval.reset()
        }
    }
}